package threadpool;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;

public class CustomThreadpoolTest {


    public static void main(String[] args) throws InterruptedException {

        CustomPool customPool = new CustomPool(4);

        for (int i = 0; i <10; i++) {
            customPool.submit(new UserTask(i));
        }

    }

}

class UserTask implements Runnable{

    private final int taskId;

    public UserTask(int taskId) {
        this.taskId = taskId;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+",user任务执行了,任务id: " + taskId);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}




class CustomPool{
    ArrayBlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<>(100);

    public CustomPool(int size) {

        // 在线程池构造时，即创建size个工作线程并启动
        for (int i = 0; i < size; i++) {
            new Thread(new Worker(taskQueue)).start();
        }
    }

    public void submit(Runnable task) throws InterruptedException {
        taskQueue.put(task);
    }
}





class Worker implements Runnable{

    ArrayBlockingQueue<Runnable> taskQueue;

    public Worker(ArrayBlockingQueue<Runnable> taskQueue) {
        this.taskQueue = taskQueue;
    }

    @Override
    public void run() {
        while(true) {
            try {

                Runnable userTask = taskQueue.take();
                userTask.run();

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
